<?php
// +----------------------------------------------------------------------
// | 文档关联 自定义服务
// +----------------------------------------------------------------------
// | 主要服务于文档关联数据处理
// +----------------------------------------------------------------------
// | 错误编码头 250xxx
// +----------------------------------------------------------------------


namespace common\service;


use common\model\DocumentRelationModel;
use common\validate\Options;
use support\ErrorCode;
use support\SingletonTrait;
use teamones\Request;

class DocumentRelationService
{
    /**
     * @var DocumentRelationModel
     */
    private $documentRelationModel;

    // 单例工具
    use SingletonTrait;

    public function __construct()
    {
        $this->documentRelationModel = model(DocumentRelationModel::class);
    }

    /**
     * 创建文档
     * @param $param
     * @param $tenantId
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function createDocument($param, $tenantId)
    {
        // 创建项目

        $requestData = [
            "param" => [
                "filter" => [
                    "name" => $param['data']['item']['name'],
                    "tenant_id" => $tenantId,
                ]
            ]
        ];
        $docItemResult = teamones_request('teamones-doc', 'item/find_by_name', $requestData);
        if (empty($docItemResult) || empty($docItemResult['data'])) {
            $requestData = [
                "data" => $param['data']['item']
            ];
            $docItemResult = teamones_request('teamones-doc', 'item/create', $requestData);
        }
        $docItem = $docItemResult['data'];
        $param['data']['relation_data']['item_id'] = $docItem['id'];

        //创建目录 list
        $itemCatalogId = "";
        $parentId = 0;
        if (isset($param['data']['catalogs']) && count($param['data']['catalogs']) > 0) {
            $parentId = 0;
            foreach ($param['data']['catalogs'] as $catalog) {
                $requestData = [
                    'param' => [
                        'filter' => [
                            'name' => $catalog['name'],
                            'parent_id' => $parentId,
                            'item_id' => $docItem['id']
                        ]
                    ]
                ];
                $docCatalogResult = teamones_request('teamones-doc', 'catalog/find_by_name', $requestData);
                if (empty($docCatalogResult) || empty($docCatalogResult['data'])) {
                    $catalog['item_id'] = $docItem['id'];
                    $catalog['parent_id'] = $parentId;
                    $requestData = [
                        'data' => $catalog,
                    ];
                    $docCatalogResult = teamones_request('teamones-doc', 'catalog/create', $requestData);
                }
                $parentId = $docCatalogResult['data']['id'];
                $itemCatalogId .= $parentId . ",";
            }
        }
        $param['data']['relation_data']['item_catalog_id'] = trim($itemCatalogId, ',');
        $param['data']['post_content']['item_id'] = $docItem['id'];
        $param['data']['post_content']['catalog_id'] = $parentId;
        //创建文章
        $requestData = [
            'data' => $param['data']['post_content']
        ];
        $docPostResult = teamones_request('teamones-doc', 'post/create', $requestData);

        if (empty($docPostResult) || empty($docPostResult['data'])) {
            throw_strack_exception('create document error',);
        }
        $docPost = $docPostResult['data'];

        $param['data']['relation_data']['post_id'] = $docPost['id'];
        $param['data']['relation_data']['relation_id'] = $param['data']['relation_data']['relation_id'] ?? create_uuid();

        //插入关联记录

        $res = $this->documentRelationModel->addItem($param['data']['relation_data']);

        if ($res === false) {
            throw_strack_exception($this->documentRelationModel->getError(), ErrorCode::DOCUMENT_RELATION_CREATE_FAILURE);
        }
        $res['post'] = $docPost;
        return $res;
    }

    /**
     * 创建项目规范系统文档
     * @param $data
     * @param $userId
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function createProjectSpecificationSystemDocument($param, $tenantId)
    {

        return $this->createDocument($param, $tenantId);
    }

    /**
     * 根据filter查询文档关联信息
     * @param $filter
     * @return array|null
     */
    public function findDocumentRelation($filter)
    {
        return $this->documentRelationModel->where($filter)->find();
    }

    /**
     * 查询文档
     * @param $param
     * @return mixed|null
     * @throws \Exception
     */
    public function findDocument($param)
    {
        $dr = $this->documentRelationModel->where($param['param']['filter'])->find();
        if (empty($dr)) {
            return null;
        }
        CommonService::getFormatAttrData($this->documentRelationModel, $dr);

        $dr['post'] = $this->getDocumentByPostId($dr['post_id']);
        return $dr;
    }

    /**
     * 更新文档
     * @param $param
     * @return mixed|null
     * @throws \Exception
     */
    public function updateDocument($param)
    {
        $dr = $this->documentRelationModel->where($param['param']['filter'])->find();
        if (empty($dr)) {
            return null;
        }
        $param['data']['id'] = $dr['post_id'];
        CommonService::getFormatAttrData($this->documentRelationModel, $dr);
        $document = teamones_request('teamones-doc', 'post/update', ['data' => $param['data']]);
        $dr['post'] = $document['data'] ?? null;
        return $dr;
    }

    /**
     * 删除文档
     * @param $param
     * @return mixed|null
     * @throws \Exception
     */
    public function deleteDocument($param)
    {
        $dr = $this->documentRelationModel->where($param['param']['filter'])->find();
        if (empty($dr)) {
            return null;
        }
        $requestData = [
            "param" => [
                "filter" => [
                    'id' => $dr['post_id']
                ]
            ]
        ];
        teamones_request('teamones-doc', 'post/delete', $requestData);
        return $this->documentRelationModel->delete($dr['id']);
    }

    /**
     * 查询项目下所有数据
     * @param $param
     * @param $tenantId
     * @return array|string
     * @throws \Exception
     */
    public function selectDocuments($param, $tenantId)
    {
        $requestData = [
            "param" => [
                "filter" => [
                    "name" => $param['param']['filter']['item_name'],
                    "tenant_id" => $tenantId,
                ]
            ]
        ];
        $docItemResult = teamones_request('teamones-doc', 'item/find_by_name', $requestData);
        if (empty($docItemResult) || empty($docItemResult['data'])) {
            return [];
        }
        $docItem = $docItemResult['data'];
        $selectResult = teamones_request('teamones-doc', 'item/select/' . $docItem['id'], null);
        return $selectResult['data'];
    }

    /**
     * 查询指定项目 指定目录下的文档
     * @param $param
     * @param int $tenantId
     * @return array|string
     * @throws \Exception
     */
    public function selectCatalogDocuments($param, int $tenantId)
    {
        $requestData = [
            "param" => [
                "filter" => [
                    "name" => $param['param']['filter']['item_name'],
                    "tenant_id" => $tenantId,
                ]
            ]
        ];
        $docItemResult = teamones_request('teamones-doc', 'item/find_by_name', $requestData);
        if (empty($docItemResult) || empty($docItemResult['data'])) {
            return [];
        }
        $docItem = $docItemResult['data'];

        $requestData = [
            'param' => [
                'filter' => [
                    'name' => $param['param']['filter']['catalog_name'],
                    'parent_id' => null,
                    'item_id' => $docItem['id']
                ]
            ]
        ];
        $catalogResult = teamones_request('teamones-doc', 'catalog/find_by_name', $requestData);

        if (empty($catalogResult) || empty($catalogResult['data'])) {
            return [];
        }
        $catalog = $catalogResult['data'];
        $requestData = [
            'param' => [
                'filter' => [
                    "item_id" => $docItem['id'],
                    'catalog_id' => $catalog['id'],
                ]
            ]
        ];
        $selectResult = teamones_request('teamones-doc', 'item/select_catalog_and_post', $requestData);
        return $selectResult['data'] ?? null;
    }

    /**
     * 通过postId查询文章
     * @param int $postId
     * @return mixed|null
     */
    public function getDocumentByPostId(int $postId)
    {
        $requestData = [
            'param' => [
                'filter' => [
                    'id' => $postId,
                ]
            ]
        ];
        $document = teamones_request('teamones-doc', 'post/find', $requestData);
        return $document['data'] ?? null;
    }


}
